package com.sidneysimmons.financially.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.sidneysimmons.financially.R;
import com.sidneysimmons.financially.Server;
import com.sidneysimmons.financially.User;
import com.sidneysimmons.financially.Validator;
import com.sidneysimmons.financially.managers.UserManager;


public class LoginActivity extends BaseActivity {
	
	private final String CLASS_NAME = this.getClass().getName();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState, CLASS_NAME);
		setContentView(R.layout.login_page);
		
		// Attach a touch listener to the links - will change color when being pressed
		TextView registerTextView = (TextView) findViewById(R.id.login_activity_textview_register);
		registerTextView.setOnTouchListener(linkTouchListener);
		
		TextView forgotPasswordTextView = (TextView) findViewById(R.id.login_activity_textview_forgot_password);
		forgotPasswordTextView.setOnTouchListener(linkTouchListener);
	}
	
	@Override
	protected void onStart() {
		super.onStart(CLASS_NAME);
	}
	
	@Override
	protected void onResume() {
		super.onResume(CLASS_NAME);

		// if logged in, redirect to main page
		if (UserManager.isLoggedIn(this)) {
			Log.i(CLASS_NAME, "User is already logged in - redirecting to AccountActivity.");
			
			Intent intent = new Intent(this, AccountActivity.class);
			startActivity(intent);
			finish();
		}
	}
	
	@Override
	protected void onPause() {
		super.onPause(CLASS_NAME);
	}
	
	@Override
	protected void onStop() {
		super.onStop(CLASS_NAME);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy(CLASS_NAME);
	}
	
	/**
	 * This method gets called when the user clicks the space outside 
	 * the text boxes.
	 * 
	 * @param view - The View object being clicked.
	 */
	public void clearFocusAndCloseKeyboard(View view) {
		EditText emailAddressView = (EditText) findViewById(R.id.login_activity_edittext_email_address);
		EditText passwordView = (EditText) findViewById(R.id.login_activity_edittext_password);
		
		// remove focus from the text fields and remove soft keyboard
		emailAddressView.clearFocus();
		passwordView.clearFocus();
		closeSoftKeyboard(emailAddressView.getWindowToken());
	}
	
	/**
	 * Handler used to catch responses from the server.
	 */
	private Handler serverHandler = new Handler() {
		public void handleMessage(Message message) {
			if (message.what == Server.COMMAND_validate_user_login) {
				if (message.arg1 == Server.RESPONSE_error) {
					int errorId = message.arg2;

					// close progress dialog and open alert
					removeDialog(DIALOG_PROGRESS);

					Bundle args = new Bundle();
					args.putString("message", getResources().getString(errorId));
					showDialog(DIALOG_ERROR, args);

					// get attention
					vibrate(150);
				} else if (message.arg1 == Server.RESPONSE_okay) {
					int messageId = message.arg2;
					
					if (messageId == R.string.server_okay_user_validation_successful) {
						Log.i(CLASS_NAME, "User validated and logged in - redirecting to CateogryListActivity.");
						removeDialog(DIALOG_PROGRESS);
						
						Intent intent = new Intent(LoginActivity.this, AccountActivity.class);
						startActivity(intent);
						finish();
					} else if (messageId == R.string.server_okay_user_validation_failed) {
						// close progress dialog and open alert
						removeDialog(DIALOG_PROGRESS);

						Bundle args = new Bundle();
						args.putString("message", getResources().getString(messageId));
						showDialog(DIALOG_ERROR, args);

						// get attention
						vibrate(150);
					}
				}
			} else if (message.what == Server.COMMAND_add_new_user) {
				if (message.arg1 == Server.RESPONSE_error) {
					int errorId = message.arg2;
					
					// close progress dialog and open alert
					removeDialog(DIALOG_PROGRESS);
					
					Bundle args = new Bundle();
					args.putString("message", getResources().getString(errorId));
					showDialog(DIALOG_ERROR, args);
					
					// get attention
					vibrate(150);
				} else if (message.arg1 == Server.RESPONSE_okay) {
					Log.i(CLASS_NAME, "User created and logged in - redirecting to CateogryListActivity.");
					removeDialog(DIALOG_PROGRESS);
					
					Intent intent = new Intent(LoginActivity.this, AccountActivity.class);
					startActivity(intent);
					finish();
				}
			} else if (message.what == Server.COMMAND_forgotten_password_email) {
				if (message.arg1 == Server.RESPONSE_error) {
					int errorId = message.arg2;

					// close progress dialog and open alert
					removeDialog(DIALOG_PROGRESS);

					Bundle args = new Bundle();
					args.putString("message", getResources().getString(errorId));
					showDialog(DIALOG_ERROR, args);

					// get attention
					vibrate(150);
				} else if (message.arg1 == Server.RESPONSE_okay) {
					int messageId = message.arg2;
					
					// close progress dialog and open alert
					removeDialog(DIALOG_PROGRESS);

					Bundle args = new Bundle();
					args.putString("message", getResources().getString(messageId));
					showDialog(DIALOG_ERROR, args);

					// get attention
					vibrate(150);
				}
			}
		}
	};
	
	/**
	 * The method gets called when the user clicks to login.
	 * 
	 * @param view - The View object being clicked.
	 */
	public void loginUser(View view) {
		// close the keyboard
		clearFocusAndCloseKeyboard(null);
		
		EditText emailAddressView = (EditText) findViewById(R.id.login_activity_edittext_email_address);
		EditText passwordView = (EditText) findViewById(R.id.login_activity_edittext_password);
		
		String emailAddress = emailAddressView.getText().toString().trim();
		String password = passwordView.getText().toString().trim();
		
		// validate email address and password
		boolean emailAddressPassed = Validator.validateEmailAddress(emailAddress);
		boolean passwordPassed = Validator.validatePassword(password);
		
		if (!emailAddressPassed) {
			String errorText = getResources().getString(R.string.login_activity_text_invalid_email_address);
			Toast.makeText(getBaseContext(), errorText, Toast.LENGTH_LONG).show();
		} else if (!passwordPassed) {
			String errorText = getResources().getString(R.string.login_activity_text_invalid_password);
			Toast.makeText(getBaseContext(), errorText, Toast.LENGTH_LONG).show();
		} else {
			int title = R.string.progress_title_logging_in;
			int message = R.string.progress_text_communicating_server;

			Bundle args = new Bundle();
			args.putString("title", getResources().getString(title));
			args.putString("message", getResources().getString(message));
			showDialog(DIALOG_PROGRESS, args);
			
			User userToValidate = new User(emailAddress, password);
			
			// Login!
			UserManager userManager = new UserManager(this);
			userManager.validateUserLogin(userToValidate, serverHandler);
		}
	}
	
	/**
	 * This method gets called when the user clicks to register.
	 * 
	 * @param view - The View object being clicked.
	 */
	public void registerNewUser(View view) {
		// close the keyboard
		clearFocusAndCloseKeyboard(null);
		
		EditText emailAddressView = (EditText) findViewById(R.id.login_activity_edittext_email_address);
		EditText passwordView = (EditText) findViewById(R.id.login_activity_edittext_password);
		
		String emailAddress = emailAddressView.getText().toString();
		String password = passwordView.getText().toString();
		
		// validate email address and password
		boolean emailAddressPassed = Validator.validateEmailAddress(emailAddress);
		boolean passwordPassed = Validator.validatePassword(password);
		
		if (!emailAddressPassed) {
			String errorText = getResources().getString(R.string.login_activity_text_invalid_email_address);
			Toast.makeText(getBaseContext(), errorText, Toast.LENGTH_LONG).show();
		} else if (!passwordPassed) {
			String errorText = getResources().getString(R.string.login_activity_text_invalid_password);
			Toast.makeText(getBaseContext(), errorText, Toast.LENGTH_LONG).show();
		} else {
			int title = R.string.progress_title_registering;
			int message = R.string.progress_text_communicating_server;

			Bundle args = new Bundle();
			args.putString("title", getResources().getString(title));
			args.putString("message", getResources().getString(message));
			showDialog(DIALOG_PROGRESS, args);
			
			// Register!
			User user = new User(emailAddress, password);
			
			UserManager userManager = new UserManager(this);
			userManager.addUserToServer(user, serverHandler);
		}
	}
	
	/**
	 * This method gets called when the user clicks the forgotten password link.
	 * 
	 * @param view - The View object being clicked.
	 */
	public void forgottenPassword(View view) {
		// close the keyboard
		clearFocusAndCloseKeyboard(null);

		EditText emailAddressView = (EditText) findViewById(R.id.login_activity_edittext_email_address);
		String emailAddress = emailAddressView.getText().toString();

		// validate email address
		boolean emailAddressPassed = Validator.validateEmailAddress(emailAddress);

		if (!emailAddressPassed) {
			String errorText = getResources().getString(R.string.login_activity_text_invalid_email_address);
			Toast.makeText(getBaseContext(), errorText, Toast.LENGTH_LONG).show();
		} else {
			int title = R.string.progress_title_sending_email;
			int message = R.string.progress_text_communicating_server;
			
			Bundle args = new Bundle();
			args.putString("title", getResources().getString(title));
			args.putString("message", getResources().getString(message));
			showDialog(DIALOG_PROGRESS, args);
			
			// Send forgotten password email
			UserManager userManager = new UserManager(this);
			userManager.sendForgottenPasswordEmail(emailAddress, serverHandler);
		}
	}
}